package com.icode.service.impl.house;

import com.icode.core.dto.house.HouseInfoDTO;
import com.icode.core.dto.house.HouseWeekDTO;
import com.icode.core.dto.house.HouseWeekTimeDTO;
import com.icode.core.dto.house.MyHouseDTO;
import com.icode.core.dto.manager.ReserveDTO;
import com.icode.core.model.house.*;
import com.icode.core.model.manage.Reserve;
import com.icode.core.model.manage.ReserveTime;
import com.icode.core.shared.DataToJson;
import com.icode.core.shared.HouseWeekHandle;
import com.icode.core.shared.JodaTimeUtils;
import com.icode.core.shared.ReserveDateHandle;
import com.icode.dao.HouseWeekDao;
import com.icode.dao.ReserveDao;
import com.icode.service.house.ReserveService;
import com.icode.service.user.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-4-15
 * Time: 上午10:00
 * To change this template use File | Settings | File Templates.
 */
@Service("reserveService")
@Transactional
public class ReserveServiceImpl implements ReserveService {

    @Autowired
    private ReserveDao reserveDao;
    @Autowired
    private HouseWeekDao houseWeekDao;
    @Autowired
    private MessageService messageService;

    @Override
    public ReserveDTO createReserveDTO(String myHouseGuid) {
        MyHouse myHouse = reserveDao.findByGuid(MyHouse.class, myHouseGuid);
        List<String> imgGuids = new ArrayList<>();
        imgGuids.add(myHouse.houseInfo().houseInfoImages().get(0).image().guid());
        HouseWeekDTO houseWeekDTO = HouseWeekDTO.toDTO(myHouse.houseWeek());
        HouseInfoDTO houseInfoDTO = new HouseInfoDTO(myHouse.houseInfo().guid(), myHouse.houseInfo().baseInfo().houseName(), imgGuids);
        ReserveDTO reserveDTO = new ReserveDTO("", "", "", "", "", myHouse.houseInfo().buildingType().houseBase().title(), "", "", "", "notReserve", houseWeekDTO, houseInfoDTO, String.valueOf(myHouse.buyNum()), null, null);
        return reserveDTO;
    }


    @Override
    public boolean addReserveDTO(String occupancyName, String IDCard, String phoneNum, String email, String peers, String remarks, String myHouseGuid, String guids) {
        boolean result = true;
        try {
            MyHouse myHouse = reserveDao.findByGuid(MyHouse.class, myHouseGuid);
            Reserve reserve = new Reserve(occupancyName, IDCard, phoneNum, email, peers, remarks, "notReserve", String.valueOf(myHouse.buyNum()), JodaTimeUtils.getTime("yyyy-MM-dd"));
            reserve.initReserve(myHouse.houseInfo(), myHouse.houseWeek(), myHouse.userInfo());
            String[] guid = guids.split(",");
            List<ReserveTime> reserveTimes = new ArrayList<>();
            for (String HouseWeekTimeguid : guid) {
                HouseWeekTime houseWeekTime = reserveDao.findByGuid(HouseWeekTime.class, HouseWeekTimeguid);
                int days = JodaTimeUtils.getValueOfTwoDate(houseWeekTime.start(), houseWeekTime.end());
                int totalDays = myHouse.days() + days;
                if (totalDays > 7) {
                    return false;
                }
                houseWeekTime.status(false);
                MyHouseStatus myHouseStatus = MyHouseStatus.ACTIVITY;
                ReserveTime reserveTime = new ReserveTime(reserve, houseWeekTime, myHouseStatus);
                reserveTimes.add(reserveTime);
                myHouse.updateDays(days);
            }
            reserve.initReserveTime(reserveTimes);
//            myHouse.setMyHouseStatus(MyHouseStatus.BOOKING);
            reserveDao.saveOrUpdate(reserve);
            messageService.sendReserveSuccess(reserve);//如果成功发送短息
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

    private void changeStatusForWeekTime(Iterator<HouseWeekTimeDTO> iterator) {
        List<String> weekTimeGuids = new ArrayList<>();
        while (iterator.hasNext()) {
            HouseWeekTimeDTO houseWeekTimeDTO = iterator.next();
            weekTimeGuids.add(houseWeekTimeDTO.getGuid());
        }
        houseWeekDao.updateStateForHouseWeekTimeByGuids(weekTimeGuids);
    }

    @Override
    public List<ReserveDTO> findAllReServe() {
        List<Reserve> reserves = reserveDao.findAllAndOrder();
        List<ReserveDTO> reserveDTOs = ReserveDTO.toDTOs(reserves);
        return reserveDTOs;
    }

    @Override
    public void changeReserveStatus(String status, String guid) {
        reserveDao.changeReserveStatus(status, guid);
    }

    @Override
    public List<HouseWeekTimeDTO> houseWeekTimeByMonth(String month, String houseWeekGuid, HttpServletResponse response) {
        HouseWeek houseWeek = reserveDao.findByGuid(HouseWeek.class, houseWeekGuid);
        List<HouseWeekTime> houseWeekTimes = reserveDao.findHouseWeekTimeBy(month, houseWeek);
        return ReserveDateHandle.exceptUselessHouseWeekTime(HouseWeekTimeDTO.toDTOs(houseWeekTimes));
//        DataToJson.houseWeekTimeByMonthToJson(houseWeekTimeDTOs, response);
    }

    @Override
    @Scheduled(cron = "0 0 12 31 12 ?")
    //每年12月31日将当年已成功入住的房子的预定周次时间状态设为true  秒 分 时 日 月 星期
    public void clearReserve() {
        List<Reserve> reserves = reserveDao.findReserved();
        for (Reserve r : reserves) {
            for (HouseWeekTime h : r.houseWeek().houseWeekTimes()) {
                h.status(true);
            }
            reserveDao.saveOrUpdate(r);
        }
    }

    @Override
    public ReserveDTO createReserveDTOForRent(String rentGuid) {
        Rent rent = reserveDao.findByGuid(Rent.class, rentGuid);
        MyHouse myHouse = rent.myHouse();
        List<String> imgGuids = new ArrayList<>();
        imgGuids.add(myHouse.houseInfo().houseInfoImages().get(0).image().guid());
        String houseBaseName = myHouse.houseInfo().buildingType().houseBase().title();
        HouseInfoDTO houseInfoDTO = new HouseInfoDTO(myHouse.houseInfo().guid(), myHouse.houseInfo().baseInfo().houseName(), imgGuids);
        ReserveDTO reserveDTO = new ReserveDTO(houseBaseName, houseInfoDTO, rent.checkInDate(), rent.leaveDate());
        return reserveDTO;
    }

    @Override
    public void getWeekTimesByHouseInfoGuid(String houseInfoGuid, HttpServletResponse response) {
        Reserve reserve = houseWeekDao.findReserveByHouseInfoGuid(houseInfoGuid);
        DataToJson.createWeekTimesByReserve(reserve, response);
    }

    @Override
    public List<ReserveDTO> findByMyHouseguid(String myhouseguid) {
        List<ReserveDTO> reserveDTOs = new ArrayList<>();
        MyHouse myHouse = reserveDao.findByGuid(MyHouse.class, myhouseguid);
        if (myHouse.myHouseStatus().equals(MyHouseStatus.ACTIVITY)) {
            List<Reserve> reserves = reserveDao.findAllByMyHouseDTO(myHouse);
            if (reserves != null) {
                reserveDTOs = ReserveDTO.toDTOs(reserves);
            }
        }
        return reserveDTOs;
    }

    @Override
    public List<ReserveDTO> findReserveByUserInfoUsername(String username) {
        List<Reserve> reserves = reserveDao.findReserveByUserInfoUsername(username);
        List<ReserveDTO> reserveDTOs = new ArrayList<>();
        if (reserves != null){
            reserveDTOs = ReserveDTO.toDTOs(reserves);
        }
        return reserveDTOs;
    }
}
